package jp.co.dailyReport.project.action;

import java.io.IOException;
import java.util.Vector;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.validator.DynaValidatorForm;
import jp.co.dailyReport.DataUnavailableException;
import jp.co.dailyReport.project.Project;
import jp.co.dailyReport.project.ProjectManager;
import jp.co.dailyReport.project.PjStaff;
import jp.co.dailyReport.project.PjStaffManager;
import jp.co.dailyReport.staff.Staff;
import jp.co.dailyReport.staff.StaffManager;
import jp.co.dailyReport.workItem.WorkItem;
import jp.co.dailyReport.workItem.WorkItemManager;
import jp.co.dailyReport.customer.Customer;
import jp.co.dailyReport.customer.CustomerManager;
import jp.co.dailyReport.SystemCalendar;
import jp.co.dailyReport.Utilities;
import jp.co.dailyReport.PermissionException;

/**
 * ﾌﾟﾛｼﾞｪｸﾄ情報登録確認ページのボタン（戻る、登録）
 * が押されたときの処理を管理するクラスです。
 */
public class ProjectAddCompletionAction extends Action {

	private static Logger log = Logger.getLogger(ProjectAddCompletionAction.class);

	/**
	 * ﾌﾟﾛｼﾞｪｸﾄ情報登録確認ページで押されるボタン（戻る、登録）
	 * によって、実行する処理を制御します。<BR><BR>
	 * 
	 * 「戻る」ボタンが押された場合の処理：<BR>
	 * 取引先情報、社員情報を取得します<BR><BR>
	 * 「登録」ボタンが押された場合の処理：<BR>
	 * プロジェクト情報、作業項目情報、プロジェクト参加メンバー情報をDBに登録します。<BR>
	 * 
	 * @param mapping このインスタンスを選択するために使用したActionMapping
	 * @param form 存在するならば、このリクエストのためのActionForm Bean
	 * @param request 処理しているHTTPリクエスト
	 * @param response 処理しているHTTPレスポンス
	 * @return ActionForwardインスタンス
	 * @throws IOException, ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		 throws IOException, ServletException{

		log.debug("ProjectAddConfirmAction start");
		String target = null;

		if(request.getParameter("addCompletion") != null){
			target = "addCompletion";
			projectAddCompletion(form, request);
		} else if(request.getParameter("returnAdd") != null){
			target = "returnAdd";
			projectReturnAdd(form, request);
		}

		log.debug("ProjectAddConfirmAction end");
		return mapping.findForward(target);
	}

	private void projectAddCompletion(ActionForm form, HttpServletRequest request){

		HttpSession session = request.getSession();
		log.debug("session.getId() = " + session.getId());
		Staff staff = (Staff)session.getAttribute("LoginStaff");
		Vector pjStaffList = (Vector)session.getAttribute("pjStaffList");
		Vector pjWorkItemList = (Vector)session.getAttribute("pjWorkItemList");
		Staff[] staffs = (Staff[])pjStaffList.toArray(new Staff[0]);
		PjStaff[] pjStaffs = new PjStaff[staffs.length];
		WorkItem[] workItems = (WorkItem[])pjWorkItemList.toArray(new WorkItem[0]);
		Project project = new Project();
		DynaValidatorForm doProjectActionForm = (DynaValidatorForm)form;

		Calendar periodStart = Utilities.getCalendarTime(
		((Integer)doProjectActionForm.get("periodStartY")).intValue(),
		((Integer)doProjectActionForm.get("periodStartM")).intValue(),
		((Integer)doProjectActionForm.get("periodStartD")).intValue(),
		0,0);

		Calendar periodEnd = Utilities.getCalendarTime(
		((Integer)doProjectActionForm.get("periodEndY")).intValue(),
		((Integer)doProjectActionForm.get("periodEndM")).intValue(),
		((Integer)doProjectActionForm.get("periodEndD")).intValue(),
		0,0);

		project.setPeriodStart(periodStart);
		project.setPeriodEnd(periodEnd);
		project.setCustomerId(((Integer)doProjectActionForm.get("customerId")).intValue());
		project.setName((String)doProjectActionForm.get("name"));
		project.setOutline((String)doProjectActionForm.get("outline"));
		project.setPjCustomerStaff((String)doProjectActionForm.get("pjCustomerStaff"));
		project.setPLStaffId(((Integer)doProjectActionForm.get("pLStaffId")).intValue());

		try{
			ProjectManager.insert(staff,project);
			int projectId = ProjectManager.loadMaxID();
			for(int i=0;i<staffs.length;i++){
				if(!PjStaffManager.isExist(projectId,staffs[i].getStaffId())){
					pjStaffs[i] = new PjStaff();
					pjStaffs[i].setProjectId(projectId);
					pjStaffs[i].setStaffId(staffs[i].getStaffId());
					PjStaffManager.insert(pjStaffs[i]);
				}
			}
			for(int i=0;i<workItems.length;i++){
				workItems[i].setProjectId(projectId);
				WorkItemManager.insert(workItems[i]);
			}
		} catch(PermissionException pe) {
			log.error(pe.getMessage());
		} catch(DataUnavailableException due) {
			log.error(due.getMessage());
		}

	}

	private void projectReturnAdd(ActionForm form, HttpServletRequest request) {

		Customer[] customerList = null;
		Staff[] staffList = null;

		try {
			customerList = CustomerManager.load();
			staffList = StaffManager.load();
		} catch(DataUnavailableException due) {
			log.error(due.getMessage());
		}

		request.setAttribute("customerList", customerList);
		request.setAttribute("staffList", staffList);
		request.setAttribute("staff", new Staff());
		request.setAttribute("systemCalendar", new SystemCalendar());
	}
}
